// components/progress-bar/progress-bar.js
let movableAreaWidth = 0;
let movableViewWidth = 0;
const backgroundAudioManager = wx.getBackgroundAudioManager();
let currentSec = -1; // 当前的秒数
let duration = 0; // 当前歌曲的总时长
let isMoving = false; // 表示当前的进度条是否在移动（拖拽），解决当进度条拖动时和timeUpdate事件冲突的问题
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        isSame: Boolean
    },

    /**
     * 组件的初始数据
     */
    data: {
        showTime: {
            currentTime: "00:00",
            totalTime: "00:00"
        },
        movableDis: 0,
        progress: 0
    },

    lifetimes: {
        ready() {
            if (this.properties.isSame && this.data.showTime.totalTime == "00:00") {
                this._setTime();
            }
            this._getMovableDis();
            this._bindBgmEvent();
        },
    },

    /**
     * 组件的方法列表
     */
    methods: {
        // 移动滚动条时
        onChange(e) {
            // console.log(e);
            // 拖动产生的效果
            if (e.detail.source == "touch") {
                this.data.progress = e.detail.x / (movableAreaWidth - movableViewWidth) * 100;
                this.data.movableDis = e.detail.x;
                isMoving = true;
            }
        },
        // 滚动条拖动停止时
        onTouchEnd(e) {
            const currentTime = backgroundAudioManager.currentTime;
            const currentTimeFmt = this._dateFormat(currentTime);
            this.setData({
                movableDis: this.data.movableDis,
                progress: this.data.progress,
                ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`
            });
            // 调整前的歌曲进度
            const sec = duration * this.data.progress / 100;
            backgroundAudioManager.seek(sec);
            isMoving = false;
        },
        // 获得当前可移动的宽度
        _getMovableDis() {
            const query = this.createSelectorQuery();
            query.select(".movable-area").boundingClientRect();
            query.select(".movable-view").boundingClientRect();
            query.exec((rect) => {
                movableAreaWidth = rect[0].width;
                movableViewWidth = rect[1].width;
                // console.log(movableAreaWidth, movableViewWidth);
            });
        },
        // 绑定背景音乐事件
        _bindBgmEvent() {
            backgroundAudioManager.onCanplay(() => {
                console.log("onCanplay");
                // 获取音乐播放时长
                if (typeof backgroundAudioManager.duration != "undefined") {
                    this._setTime();
                } else {
                    setTimeout(() => {
                        this._setTime();
                    }, 1000);
                }
            });

            backgroundAudioManager.onPlay(() => {
                console.log("onPlay");
                isMoving = false;
                this.triggerEvent("musicPlay");
            });

            backgroundAudioManager.onTimeUpdate(() => {
                console.log("onTimeUpdate");
                if (!isMoving) {
                    const currentTime = backgroundAudioManager.currentTime;
                    const duration = backgroundAudioManager.duration;
                    const sec = currentTime.toString().split(".")[0];
                    if (sec != currentSec) {
                        const currentTimeFmt = this._dateFormat(currentTime);
                        // 播放进度
                        const movableDis = (movableAreaWidth - movableViewWidth) * currentTime / duration;
                        this.setData({
                            movableDis,
                            progress: currentTime / duration * 100,
                            ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`
                        });
                        currentSec = sec;
                        // 联动歌词
                        this.triggerEvent("timeUpdate", {
                            currentTime
                        });
                    }
                }
            });

            backgroundAudioManager.onPause(() => {
                console.log("Pause");
                this.triggerEvent("musicPause");
            });

            backgroundAudioManager.onStop(() => {
                console.log("onStop");
            });

            backgroundAudioManager.onEnded(() => {
                console.log("onEnded");
                this.triggerEvent("musicEnd");
            });


            backgroundAudioManager.onWaiting(() => {
                console.log("onWaiting");
            });

            backgroundAudioManager.onError((res) => {
                console.error(res.errMsg);
                console.error(res.errCode);
                wx.showToast({
                    title: `错误${res.errCode}`,
                })
            });
        },
        //  设置音乐播放总时长
        _setTime() {
            duration = backgroundAudioManager.duration;
            const durationFormat = this._dateFormat(duration);
            this.setData({
                ['showTime.totalTime']: `${durationFormat.min}:${durationFormat.sec}`
            });
        },
        // 时间格式化
        _dateFormat(duration) {
            const min = Math.floor(duration / 60);
            const sec = Math.floor(duration % 60);
            return {
                "min": this._parse0(min),
                "sec": this._parse0(sec)
            }
        },
        // 补0
        _parse0(sec) {
            return sec < 10 ? "0" + sec : sec;
        }
    }
})